package com.cheerscpl;

import com.cheerscpl.protocol.Channels;
import com.cheerscpl.protocol.model.DataPacket;
import io.netty.channel.socket.SocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.util.UUID;


/**
 * Created by chenpuliang on 2017/6/4.
 */
public class Task implements Serializable{

    public static final Logger logger = LoggerFactory.getLogger(Task.class);

    private static final long serialVersionUID = -5083295612820037682L;

    final String uuid;

    final String name;

    final DataPacket dataPacket;

    public Task(final String uuid, final String name, final DataPacket dataPacket) {
        this.uuid = uuid;
        this.name = name;
        this.dataPacket = dataPacket;
    }

    public static class TaskBuilder {
        private String uuid;
        private String name;
        private DataPacket dataPacket;

        public TaskBuilder() {
            this.uuid = UUID.randomUUID().toString().replace("-", "");
        }

        public TaskBuilder dataPacket(DataPacket dataPacket) {
            this.name = dataPacket.getDevId();
            this.dataPacket = dataPacket;
            return this;
        }

        public Task build(){
            return new Task(this.uuid, this.name, this.dataPacket);
        }
    }

    public String getUuid() {
        return uuid;
    }

    public String getName() {
        return name;
    }

    public DataPacket getDataPacket() {
        return dataPacket;
    }

    /**
     * 发送命令方法
     */
    public void send(){
        DataPacket dataPacket = this.getDataPacket();
        if(null != dataPacket){
            String devId = dataPacket.getDevId();
            SocketChannel socketChannel = (SocketChannel) Channels.getChannel(devId);
            if(socketChannel == null){
                logger.error("request device: {} err.", devId);
            }else{
                if(socketChannel.isWritable()){
                    socketChannel.writeAndFlush(dataPacket);
                }else {
                    logger.error("channel is broken, deviceId: " + devId);
                }
            }
        }
    }
}
